// 路由配置文件：src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
// 导入页面组件（使用实际存在的文件）
import login from '../views/Login.vue'  // 注意文件名大小写与实际一致
import BusinessMessages from '../views/BusinessMessages.vue'
import ContractTemplates from '../views/ContractTemplates.vue'
import Favorites from '../views/Favorites.vue'
import Orders from '../views/orders/index.vue'
import addOrders from '../views/orders/addOrders.vue'
import report from '../views/report.vue'
import Profile from '../views/Profile.vue'
import SystemMessages from '../views/SystemMessages.vue'

// 定义路由规则 - 使用现有组件作为系统首页
const routes = [
    {
        path: '/login',
        name: 'Login',
        component: login,  // 登录页
        meta: {
            requiresAuth: false
        }
    },
    {
        path: '/orders/add',
        name: 'addOrders',
        component: addOrders,
        meta: {
            requiresAuth: true
        }
    },
    {
        path: '/',
        // 使用合同模板页面作为系统首页（可根据实际情况替换）
        name: 'ContractTemplates',
        component: ContractTemplates,
        meta: {
            requiresAuth: true
        }
    },
    {
        path: '/business-messages',
        name: 'BusinessMessages',
        component: BusinessMessages,
        meta: {
            requiresAuth: true
        }
    },
    {
        path: '/favorites',
        name: 'Favorites',
        component: Favorites,
        meta: {
            requiresAuth: true
        }
    },
    {
        path: '/orders',
        name: 'Orders',
        component: Orders,
        meta: {
            requiresAuth: true
        }
    },
    {
        path: '/profile',
        name: 'Profile',
        component: Profile,
        meta: {
            requiresAuth: true
        }
    },
    {
        path: '/system-messages',
        name: 'SystemMessages',
        component: SystemMessages,
        meta: {
            requiresAuth: true
        }
    },
    {
        path: '/admin/report',
        name: 'report',
        component: report,
        meta: {requiresAuth: true, role: 'SUPER_ADMIN'}, // 仅超级管理员可访问
    },
    {
        path: '/admin',
        name: 'Admin',
        component: () => import('../views/Admin.vue'),
        meta: {requiresAuth: true, role: 'ADMIN'}
    },
    // 重定向到登录页 - Vue Router 4 语法
    {
        path: '/:pathMatch(.*)*',
        redirect: '/login'
    }
]

// 创建路由实例
const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const isLoggedIn = localStorage.getItem('token') !== null

    if (to.meta.requiresAuth && !isLoggedIn) {
        next('/login')
    } else if (to.path === '/login' && isLoggedIn) {
        // 已登录时访问登录页，跳转到系统首页（这里是ContractTemplates）
        next('/')
    } else {
        next()
    }
})

export default router
